<?php
class User_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    /**
     * Get all users
     * @return mixed
     */
    function getAll() {
        $query = $this->db->get('pr_users');
        return $query->result_array();
    }

    /**
     * Add a New User
     */
    function insert($level) {
        $this->username = $this->input->post('username');
        $this->password = $this->input->post('password');
        $this->level = $level;

        $this->db->insert('pr_users', $this);
    }

    /**
     * Login
     * @return mixed
     */
    function login() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $query = $this->db->get_where('pr_users', array('username' => $username, 'password' => $password));
        return $query->row_array();
    }

    /**
     * Change your password
     * @param $username
     * @return bool
     */
    function changePassword($username) {
        $oldpass = $this->input->post('oldpass');
        $newpass = $this->input->post('newpass');
        // Check whether the password is true
        $query = $this->db->get_where('pr_users', array('username' => $username, 'password' => $oldpass));
        $query = $query->row_array();

        if (!empty($query)) {
            $this->db->update('pr_users', array('password' => $newpass), array('username' => $username));
            return TRUE;
        } else {
            return FALSE;
        }

    }

    /**
     * Select the specific user
     * @return mixed
     */
    function select() {
        $uid = $this->input->get('uid');
        $query = $this->db->get_where('pr_users', array('uid' => $uid));
        return $query->row_array();
    }

    /**
     * Edit the specific user
     */
    function edit() {
        $uid = $this->input->get('uid');
        $password = $this->input->post('password');
        $this->password = $password;
        $this->db->update('pr_users', $this, array('uid' => $uid));
    }

    /**
     * Delete the specific user
     */
    function delete() {
        $uid = $this->input->get('uid');
        $this->db->delete('pr_users', array('uid' => $uid));
    }
}